import string
import random
from flask import Blueprint, request, jsonify, session
from flask_mail import Message
from extension import email, db
from models.auth import EmailCaptchaModel, UserModel
from .forms import RegistrationForm, LoginForm
from werkzeug.security import generate_password_hash, check_password_hash

bp = Blueprint('auth', __name__, url_prefix='/auth')

@bp.route('/login', methods=['POST'])
def login():
    form = LoginForm(request.form)
    if form.validate():
        email = form.email.data
        password = form.password.data
        user = UserModel.query.filter_by(email=email).first()
        if not user:
            return jsonify({
                'status': 'fail',
                'code': 400,
                'message': '未注册',
            })
        else:
            if check_password_hash(user.password, password):
                session['user_id'] = user.id
                return jsonify({
                    'status': 'success',
                    'code': 200,
                    'data': {
                        'username': user.username,
                        'email': user.email,
                    },
                })
            else:
                return jsonify({
                    'status': 'fail',
                    'code': 400,
                    'message': '邮箱或密码错误',
                })
    else:
        return jsonify({
            'status': 'fail',
            "code": 400,
            "message": form.errors
        })

@bp.route('/register', methods=['GET', 'POST'])
def register_user():
    if request.method == 'GET':
        return 'register'
    elif request.method == 'POST':
        form = RegistrationForm(request.form)

        if form.validate():
            username = form.username.data
            password = form.password.data
            email = form.email.data
            user = UserModel(username=username, password=generate_password_hash(password), email=email)
            db.session.add(user)
            db.session.commit()

            return jsonify({
                'status': 'success',
                "code": 200,
                "data": {
                    "username": username,
                    "email": email,
                },
                "message": "注册成功",
            })
        else:
            print(form.errors)
            return jsonify({
                'status': 'fail',
                "code": 400,
                "message": form.errors
            })
    return None


@bp.route('/captcha/email')
def captcha_email():
    email = request.args.get('email')

    source = string.digits * 4
    captcha = ''.join(random.sample(source, 4))
    print(captcha, email)

    # 发送邮件
    # message = Message(subject='code', recipients=[email], body=f'你的验证码是：{captcha}')
    # email.send(message)

    email = EmailCaptchaModel(email=email, captcha=captcha)
    db.session.add(email)
    db.session.commit()

    return jsonify({'code': 200, 'message': 'success', 'data': True })

@bp.route('/email')
def send_email():
    message = Message(subject='email test', recipients=['liuqiong_0106@126.com'], body='hello world')
    email.send(message)
    return 'email send success'